<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2024/2/22
 * Time: 10:48
 */

namespace app\api\controller;

use app\api\model\Goods AS GoodsModel;
use app\api\model\GoodsCate;
use app\api\model\GoodsCollect;
use app\api\model\GoodsAttr;
use app\api\model\GoodsPackaging;
use app\api\model\GoodsSpec;

class Goods extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 首页分类&商品
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function indexGoodsData(){
        // 推荐一级分类
        $firstCateWhere = [
            'cate_level' => 1,
            'cate_recommend' => 1
        ];
        $firstField = 'cate_id, cate_name_en, cate_name_es, cate_name_tp, cate_image';
        $firstRecommendGoodsCate = GoodsCate::selectGoodsCate($firstCateWhere, $firstField);

        if($firstRecommendGoodsCate){
            $firstCateIds = array_column($firstRecommendGoodsCate, 'cate_id');
            // 二级分类
            $secondCateWhere = [
                'cate_pid' => ['IN', $firstCateIds]
            ];
            $secondField = 'cate_id, cate_name_en, cate_name_es, cate_name_tp, cate_pid';
            $secondGoodsCate = GoodsCate::selectGoodsCate($secondCateWhere, $secondField);

            // 商品
            $goodsWhere = [
                'goods_f_cate' => ['IN', $firstCateIds]
            ];
            $goodsField = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, 
            goods_cu_price, goods_cu, goods_f_cate, goods_s_cate';
            $goods = GoodsModel::selectData($goodsWhere, $goodsField, 1, 0)->toArray();

            // 商品&收藏
            if($goods){
                // 我的收藏
                $myCollect = GoodsCollect::selectData(['collect_user_id' => $this->user_id], 'collect_goods_id');
                foreach ($goods as $k => $v){
                    $_isCollect = 2; // 未收藏
                    if($myCollect){
                        foreach ($myCollect as $k1 => $v1){
                            if($v1['collect_goods_id'] == $v['goods_id']){
                                $_isCollect = 1;
                            }
                        }
                    }
                    $goods[$k]['isCollect'] = $_isCollect;
                }
            }

            // 一级分类&二级分类
            foreach ($firstRecommendGoodsCate as $k2 => $v2){
                $_secondCate = [];
                if($secondGoodsCate){
                    foreach ($secondGoodsCate as $k3 => $v3){
                        if($v2['cate_id'] == $v3['cate_pid']){
                            $_secondCate[] = $v3;
                        }
                    }
                }
                $firstRecommendGoodsCate[$k2]['secondCate'] = $_secondCate;
            }

            // 分类&商品
            foreach ($firstRecommendGoodsCate as $k4 => $v4){
                $_goods = [];
                $_goodsNumber = 0;
                if($v4['secondCate']){
                    if($goods){
                        foreach ($goods as $k5 => $v5){
                            if($v5['goods_s_cate'] == $v4['secondCate'][0]['cate_id'] && $_goodsNumber < 6){
                                $_goods[] = $v5;
                                $_goodsNumber++;
                            }
                        }
                    }
                }else{
                    if($goods){
                        foreach ($goods as $k6 => $v6){
                            if($v6['goods_f_cate'] == $v4['cate_id'] && $_goodsNumber < 6){
                                $_goods[] = $v6;
                                $_goodsNumber++;
                            }
                        }
                    }
                }
                $firstRecommendGoodsCate[$k4]['goods'] = $_goods;
            }
            return json(['status' => 200, 'msg' => $firstRecommendGoodsCate]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }

    }

    /**
     * 首页推荐商品
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function recommendGoods(){
        // 商品
        $where = [
            'goods_recommend' => 1
        ];
        $field = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, 
            goods_cu_price, goods_intro_en, goods_intro_es, goods_intro_tp';
        $goods = GoodsModel::selectData($where, $field)->toArray();

        // 我的收藏
        $myCollect = GoodsCollect::selectData(['collect_user_id' => $this->user_id], 'collect_goods_id');

        if($goods){
            foreach ($goods as $k => $v){
                $_isCollect = 2; // 未收藏
                if($myCollect){
                    foreach ($myCollect as $k1 => $v1){
                        if($v1['collect_goods_id'] == $v['goods_id']){
                            $_isCollect = 1;
                        }
                    }
                }
                $goods[$k]['isCollect'] = $_isCollect;
            }
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 200, 'msg' =>[]]);
        }
    }

    /**
     * 商品属性
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsAttr(){
        $data = GoodsAttr::selectData();
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 根据规格ID，获取价格
     * spec_id    规格ID
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getGoodsPriceBySpec(){
        $spec_id = input('spec_id');

        if(!$spec_id) return json(['status' => 0, 'msg' => $this->lanMsg->specIDErr[$this->lanType]]);

        $spec = GoodsSpec::get($spec_id);
        return json(['status' => 200, 'msg' => $spec]);
    }

    /**
     * 商品列表
     * page     页码
     * keyword  搜索关键字
     * fCate    一级分类
     * sCate    二级分类
     * tCate    三级分类
     * attr     属性
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList(){
        $page = input('page') ? input('page') : 1;
        $keyword = input('keyword');
        $fCate = input('fCate');
        $sCate = input('sCate');
        $tCate = input('tCate');
        $attr = input('attr');

        $where = [];

        if($keyword){
            if($this->lanType == 0){
                $goodsName = 'goods_name_en';
            }elseif($this->lanType == 1){
                $goodsName = 'goods_name_es';
            }else{
                $goodsName = 'goods_name_tp';
            }
            $where[$goodsName] = ['LIKE', '%' . $keyword . '%'];
        }

        if($fCate) $where['goods_f_cate'] = $fCate;
        if($sCate) $where['goods_s_cate'] = $sCate;
        if($tCate) $where['goods_t_cate'] = $tCate;
        if($attr) $where['goods_attr'] = ['IN', $attr];

        // 如果没有搜索或筛选，就展示推荐的
//        if(!$where){
//            $where['goods_recommend'] = 1;
//        }
        $field = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, 
        goods_cu_price, goods_intro_en, goods_intro_es, goods_intro_tp';
        $goods = GoodsModel::selectData($where, $field, $page, 2)->toArray();

        if($goods){
            // 我的收藏
            $myCollect = GoodsCollect::selectData(['collect_user_id' => $this->user_id], 'collect_goods_id');
            foreach ($goods as $k => $v){
                $_isCollect = 2; // 未收藏
                if($myCollect){
                    foreach ($myCollect as $k1 => $v1){
                        if($v1['collect_goods_id'] == $v['goods_id']){
                            $_isCollect = 1;
                        }
                    }
                }
                $goods[$k]['isCollect'] = $_isCollect;
            }
            $count = GoodsModel::countData($where);
            return json(['status' => 200, 'msg' => $goods, 'count' => $count]);
        }else{
            return json(['status' => 200, 'msg' => [], 'count' => 0]);
        }
    }

    /**
     * 商品详情
     * goods_id    商品ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsDetail(){
        $goods_id = input('goods_id');

        $where['goods_id'] = $goods_id;
        $field = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_price, goods_cu_price, goods_images, 
        goods_spec_name_en, goods_spec_name_es, goods_spec_name_es, goods_packaging, goods_intro_en, goods_intro_es, 
        goods_intro_tp, goods_detail_en, goods_detail_es, goods_detail_tp, goods_status, goods_f_cate, goods_s_cate, 
        goods_t_cate, goods_spec_name_tp';

        $goods = GoodsModel::findData($where, $field)->toArray();
        if(!$goods) return json(['status' => 0, 'msg' => $this->lanMsg->goodsIDErr[$this->lanType]]);
        if($goods['goods_status'] != 1) return json(['status' => 0, 'msg' => $this->lanMsg->goodsStatusErr[$this->lanType]]);

        // 多图
        if($goods['goods_images']){
            $goods_images = explode(',', $goods['goods_images']);
            $goods['goods_images'] = array_map(function($item){
                return http_type() . $item;
            }, $goods_images);
        }else{
            $goods['goods_images'] = [];
        }

        // 包装
        if($goods['goods_packaging']){
            $goods['goods_packaging'] = GoodsPackaging::selectData(['packaging_id' => ['IN', $goods['goods_packaging']]]);
        }else{
            $goods['goods_packaging'] = [];
        }

        // 规格
        $spec = GoodsSpec::selectData(['spec_goods_id' => $goods_id]);
        if($spec){
            $goods['spec'] = $spec;
        }else{
            $goods['spec'] = [];
        }

        // 我的收藏
        $myCollect = GoodsCollect::selectData(['collect_user_id' => $this->user_id], 'collect_goods_id')->toArray();
        $goodsCollect = 2; // 未收藏
        $collectIds = [];
        if($myCollect){
            $collectIds = array_column($myCollect, 'collect_goods_id');
            if(in_array($goods_id, $collectIds)){
                $goodsCollect = 1; // 已收藏
            }
        }
        $goods['goodsCollect'] = $goodsCollect;


        // 一级分类
        $firstGoodsCate = GoodsCate::findData(['cate_id' => $goods['goods_f_cate']], 'cate_name_en, cate_name_es, cate_name_tp');
        $goods['cateName_en'] = $firstGoodsCate['cate_name_en'];
        $goods['cateName_es'] = $firstGoodsCate['cate_name_es'];
        $goods['cateName_tp'] = $firstGoodsCate['cate_name_tp'];

        // 推荐商品，按一级分类随机找8个
        $fieldRecommend = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, goods_cu_price';
        $recommendGoods = GoodsModel::selectData(['goods_f_cate' => $goods['goods_f_cate'], 'goods_id' => ['<>', $goods_id]], $fieldRecommend);
        if($recommendGoods){
            foreach ($recommendGoods as $k => $v){
                $_isCollect = 2; // 未收藏
                if($collectIds){
                    if(in_array($v['goods_id'], $collectIds)) $_isCollect = 1;
                }
                $recommendGoods[$k]['isCollect'] = $_isCollect;
            }
            $goods['recommend_goods'] = $recommendGoods;
        }else{
            $goods['recommend_goods'] = [];
        }

        return json(['status' => 200, 'msg' => $goods]);
    }

    /**
     * 商品分类--H5
     * fCate_id    一级分类ID
     * page        页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cateGoodsForH5(){
        $fCate_id = input('fCate_id') ?: 0;
        $page  = input('page') ?: 1;

        // 所有一级分类
        $firstWhere['cate_level'] = 1;
        $firstField = 'cate_id, cate_name_en, cate_name_es, cate_name_tp';
        $fCate = GoodsCate::selectGoodsCate($firstWhere, $firstField);
        if(!$fCate) $fCate = [];

        // 一级下的所有二级分类
        $secondWhere['cate_pid'] = $fCate_id;
        $sCate = GoodsCate::selectGoodsCate($secondWhere, $firstField);
        if(!$sCate) $sCate = [];

        // 一级下所有商品
        if($fCate_id){
            $goodsWhere = ['goods_f_cate' => $fCate_id];
        }else{
            $goodsWhere = [];
        }
        $goodsField = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, goods_cu_price, goods_s_cate';
        $allGoods = GoodsModel::selectData($goodsWhere, $goodsField, $page, 2);
        if(!$allGoods) $allGoods = [];

        $goodsCount = GoodsModel::countData($goodsWhere);
        return json(['status' => 200, 'msg' => '', 'firstCate' => $fCate, 'item' => $sCate, 'goods' => $allGoods, 'count' => $goodsCount]);
    }

    /**
     * 根据二级分类ID，获取三级、商品---H5
     * fCate_id    一级分类ID
     * sCate_id    二级分类ID 全部传0
     * page        页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getContentBySecondCate(){
        $fCate_id = input('fCate_id');
        $sCate_id = input('sCate_id') ?: 0;
        $page = input('page') ?: 1;

        // 三级分类
        $thirdWhere['cate_pid'] = $sCate_id;
        $thirdField = 'cate_id, cate_name_en, cate_name_es, cate_name_tp';
        $tCate = GoodsCate::selectGoodsCate($thirdWhere, $thirdField);
        if(!$tCate) $tCate = [];

        // 产品
        if($sCate_id){
            $goodsWhere['goods_s_cate'] = $sCate_id;
        }else{
            $goodsWhere['goods_f_cate'] = $fCate_id;
        }
        $goodsField = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, goods_cu_price, goods_s_cate';
        $allGoods = GoodsModel::selectData($goodsWhere, $goodsField, $page, 2);
        if(!$allGoods) $allGoods = [];

        $goodsCount = GoodsModel::countData($goodsWhere);
        return json(['status' => 200, 'msg' => '', 'thirdCate' => $tCate, 'goods' => $allGoods, 'count' => $goodsCount]);
    }

    /**
     * 根据三级，获取商品---H5
     * fCate_id    一级分类ID
     * sCate_id    二级分类ID 全部传0
     * tCate_id    三级分类ID 全部传0
     * page        页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getContentByThirdCate(){
        $fCate_id = input('fCate_id');
        $sCate_id = input('sCate_id') ?: 0;
        $tCate_id = input('tCate_id') ?: 0;
        $page = input('page') ?: 1;

        if(!$sCate_id && !$tCate_id){ // 二级、三级都没有，就查一级下所有的
            $where['goods_f_cate'] = $fCate_id;
        }elseif ($sCate_id && !$tCate_id){ // 有二级，没三级，就查所有该二级下的所有
            $where['goods_s_cate'] = $sCate_id;
        }elseif ($sCate_id && $tCate_id){
            $where['goods_t_cate'] = $tCate_id;
        }
        $field = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, goods_cu_price, goods_s_cate';
        $allGoods = GoodsModel::selectData($where, $field, $page, 2);
        if(!$allGoods) $allGoods = [];

        $goodsCount = GoodsModel::countData($where);
        return json(['status' => 200, 'msg' => '', 'goods' => $allGoods, 'count' => $goodsCount]);
    }

    /**
     * 搜索商品---H5
     * keyWord     关键字
     * page        页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function searchGoods(){
        $keyWord = input('keyWord');
        $page = input('page');

        if($keyWord){
            if($this->lanType == 0){
                $goodsName = 'goods_name_en';
            }elseif($this->lanType == 1){
                $goodsName = 'goods_name_es';
            }else{
                $goodsName = 'goods_name_tp';
            }
            $where[$goodsName] = ['LIKE', '%' . $keyWord . '%'];
            $field = 'goods_id, goods_name_en, goods_name_es, goods_name_tp, goods_thumb, goods_price, 
        goods_cu_price, goods_intro_en, goods_intro_es, goods_intro_tp';
            $goods = GoodsModel::selectData($where, $field, $page, 2);
            if(!$goods) $goods = [];

            $goodsCount = GoodsModel::countData($where);
            return json(['status' => 200, 'msg' => $goods, 'count' => $goodsCount]);
        }else{
            return json(['status' => 200, 'msg' => [], 'count' => 0]);
        }
    }
}